using CKY.AgentPlatform.Performance;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Polly;
using System;

namespace Microsoft.Extensions.DependencyInjection
{
    /// <summary>
    /// 性能优化服务扩展
    /// </summary>
    public static class PerformanceServiceExtensions
    {
        /// <summary>
        /// 添加性能优化服务
        /// </summary>
        public static IServiceCollection AddPerformanceOptimization(this IServiceCollection services, Action<PerformanceOptions> setupAction = null)
        {
            var options = new PerformanceOptions();
            setupAction?.Invoke(options);

            // 注册性能指标收集器
            services.AddSingleton<PerformanceMetrics>();

            // 注册缓存选项
            services.AddSingleton(options.Caching);

            // 注册压缩选项
            services.AddSingleton(options.Compression);

            // 注册内存缓存（如果配置了响应缓存）
            if (options.EnableResponseCaching)
            {
                services.AddMemoryCache();
                services.AddDistributedMemoryCache();
            }

            // 注册分布式缓存（如果配置了Redis）
            if (options.EnableDistributedCaching)
            {
                services.AddStackExchangeRedisCache(redisOptions =>
                {
                    redisOptions.Configuration = options.RedisConfiguration;
                    redisOptions.InstanceName = "AgentPlatform";
                });
            }

            // 注册HTTP客户端工厂（用于外部API调用优化）
            services.AddHttpClient("OptimizedHttpClient")
                .AddPolicyHandler(GetRetryPolicy())
                .AddPolicyHandler(GetCircuitBreakerPolicy())
                .AddPolicyHandler(GetTimeoutPolicy());

            return services;
        }

        /// <summary>
        /// 使用性能优化中间件
        /// </summary>
        public static IApplicationBuilder UsePerformanceOptimization(this IApplicationBuilder app, Action<PerformanceMiddlewareOptions> setupAction = null)
        {
            var options = new PerformanceMiddlewareOptions();
            setupAction?.Invoke(options);

            // 按顺序添加性能优化中间件
            if (options.EnableResponseCompression)
            {
                app.UseMiddleware<CompressionMiddleware>();
            }

            if (options.EnableResponseCaching)
            {
                app.UseMiddleware<CachingMiddleware>();
            }

            if (options.EnablePerformanceMonitoring)
            {
                app.UseMiddleware<PerformanceMonitoringMiddleware>();
            }

            return app;
        }

        /// <summary>
        /// 获取重试策略
        /// </summary>
        private static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
        {
            return Policy<HttpResponseMessage>
                .Handle<HttpRequestException>()
                .OrResult(response => !response.IsSuccessStatusCode)
                .WaitAndRetryAsync(
                    retryCount: 3,
                    sleepDurationProvider: retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
                    onRetry: (outcome, timespan, retryAttempt, context) =>
                    {
                        // 记录重试日志
                    });
        }

        /// <summary>
        /// 获取断路器策略
        /// </summary>
        private static IAsyncPolicy<HttpResponseMessage> GetCircuitBreakerPolicy()
        {
            return Policy<HttpResponseMessage>
                .Handle<HttpRequestException>()
                .OrResult(response => response.StatusCode >= System.Net.HttpStatusCode.InternalServerError)
                .CircuitBreakerAsync(
                    handledEventsAllowedBeforeBreaking: 3,
                    durationOfBreak: TimeSpan.FromSeconds(30),
                    onBreak: (outcome, breakDelay) =>
                    {
                        // 记录断路器开启日志
                    },
                    onReset: () =>
                    {
                        // 记录断路器重置日志
                    });
        }

        /// <summary>
        /// 获取超时策略
        /// </summary>
        private static IAsyncPolicy<HttpResponseMessage> GetTimeoutPolicy()
        {
            return Policy.TimeoutAsync<HttpResponseMessage>(30);
        }
    }

    /// <summary>
    /// 性能优化配置选项
    /// </summary>
    public class PerformanceOptions
    {
        /// <summary>
        /// 启用性能监控
        /// </summary>
        public bool EnablePerformanceMonitoring { get; set; } = true;

        /// <summary>
        /// 启用响应缓存
        /// </summary>
        public bool EnableResponseCaching { get; set; } = true;

        /// <summary>
        /// 启用分布式缓存
        /// </summary>
        public bool EnableDistributedCaching { get; set; } = false;

        /// <summary>
        /// 启用响应压缩
        /// </summary>
        public bool EnableResponseCompression { get; set; } = true;

        /// <summary>
        /// Redis配置字符串
        /// </summary>
        public string RedisConfiguration { get; set; } = "localhost:6379";

        /// <summary>
        /// 缓存配置
        /// </summary>
        public CachingOptions Caching { get; set; } = new CachingOptions();

        /// <summary>
        /// 压缩配置
        /// </summary>
        public CompressionOptions Compression { get; set; } = new CompressionOptions();

        public PerformanceOptions()
        {
            // 配置默认缓存规则
            Caching.AddRule("/api/agent-platform/agents", TimeSpan.FromMinutes(5));
            Caching.AddRule("/api/agent-platform/model-configs", TimeSpan.FromMinutes(10));
            Caching.AddRule("/api/agent-platform/prompt-templates", TimeSpan.FromMinutes(15));
            Caching.AddRule("/api/agent-platform/statistics/*", TimeSpan.FromMinutes(1));
        }
    }

    /// <summary>
    /// 性能中间件配置选项
    /// </summary>
    public class PerformanceMiddlewareOptions
    {
        /// <summary>
        /// 启用性能监控中间件
        /// </summary>
        public bool EnablePerformanceMonitoring { get; set; } = true;

        /// <summary>
        /// 启用响应缓存中间件
        /// </summary>
        public bool EnableResponseCaching { get; set; } = true;

        /// <summary>
        /// 启用响应压缩中间件
        /// </summary>
        public bool EnableResponseCompression { get; set; } = true;
    }
}